using System.Collections.Generic;
using System.Linq;
using System.Text;
using FeedReaderApp.Common;
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using FeedReaderApp.DataModel;
using FeedReaderApp.Model;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.Resources;

namespace FeedReaderApp.ViewModel
{
    public class GroupedItemsViewModel : ViewModelBase
    {
        public GroupedItemsViewModel()
        {
            _feedItems = FeedsDataSource.Instance.FeedItems;
        }

        private List<FeedItem> _feedItems;
        public List<FeedItem> FeedItems 
        { 
            get { return _feedItems; }
        }

        public List<FeedDeclaration> FeedDeclarations
        {
            get { return FeedsDataSource.Instance.FeedDeclarations; }
        }

        public void Initialize()
        {
            RegisterDataSourceEvents();
            FeedsDataSource.Instance.LoadFeedsParallel(false);
            RefreshInProgress = FeedsDataSource.Instance.IsCurrentlyLoading;
        }

        private void RegisterDataSourceEvents()
        {
            FeedsDataSource.Instance.FeedItemsAdded += OnFeedItemsAdded;
            FeedsDataSource.Instance.FeedItemsCleared += OnFeedItemsCleared;
            FeedsDataSource.Instance.FeedItemsLoadingCompleted += OnFeedItemsLoadingCompleted;
        }

        public void DeRegisterDataSourceEvents()
        {
            FeedsDataSource.Instance.FeedItemsAdded -= OnFeedItemsAdded;
            FeedsDataSource.Instance.FeedItemsCleared -= OnFeedItemsCleared;
            FeedsDataSource.Instance.FeedItemsLoadingCompleted -= OnFeedItemsLoadingCompleted;
        }

        private void OnFeedItemsLoadingCompleted(object sender, FeedItemsLoadingCompletedEventArgs feedItemsLoadingCompletedEventArgs)
        {
            UIDispatcher.Execute(() =>
                                     {
                                         RefreshInProgress = false;
                                         _feedItems = FeedsDataSource.Instance.FeedItems;
                                         RaisePropertyChanged(FeedsGroupedBySourcePropertyName);
                                     });
        }

        private void OnFeedItemsAdded(object sender, FeedItemsAddedEventArgs e)
        {
            UIDispatcher.Execute(()=>
                                     {
                                         _feedItems = FeedsDataSource.Instance.FeedItems;
                                         RaisePropertyChanged(FeedsGroupedBySourcePropertyName);
                                     });
        }

        private void OnFeedItemsCleared(object sender, FeedItemsClearedEventArgs feedItemsClearedEventArgs)
        {
            UIDispatcher.Execute(()=>
                                     {
                                         _feedItems = null;
                                         RaisePropertyChanged(FeedsGroupedBySourcePropertyName);
                                     });
        }

        public const string FeedsGroupedBySourcePropertyName = "FeedsGroupedBySource";
        public List<FeedGrouping> FeedsGroupedBySource
        {
            get
            {
                if (_feedItems == null) return null;

                var query = from item in _feedItems
                            group item by item.FeedName
                            into g
                            select new FeedGrouping()
                                       {
                                           Name = g.Key,
                                           FeedItems = g.Take(5).ToList()
                                       };

                return query.ToList();

            }
        }

        private RelayCommand _refreshCommand;
        public RelayCommand RefreshCommand
        {
            get
            {
                return _refreshCommand
                    ?? (_refreshCommand = new RelayCommand(
                        () =>
                            {
                                FeedsDataSource.Instance.LoadFeedsParallel(true);
                                RefreshInProgress = FeedsDataSource.Instance.IsCurrentlyLoading;
                            }));
            }
        }

        public const string RefreshInProgressPropertyName = "RefreshInProgress";
        private bool _refreshInProgress = false;
        public bool RefreshInProgress
        {
            get
            {
                return _refreshInProgress;
            }
            set
            {
                Set(RefreshInProgressPropertyName, ref _refreshInProgress, value);
            }
        }

        public bool Share(DataRequestedEventArgs e)
        {
            if (null == FeedItems)
            {
                return false;
            }
            else
            {
                DataRequest request = e.Request;

                request.Data.Properties.Title = "Deutsche Microsoft Community Blogger";

                var sb = new StringBuilder();

                foreach (var item in FeedItems)
                {
                    var url = item.Uri;
                    sb.AppendLine("<p><h2>" + item.FeedName + "</h2></p>");
                    sb.AppendLine("<img src='" + item.InferredImageUrl + "' width='200px' alt='" + item.Title + "'/><br/><br/>");
                    sb.AppendLine("<a href='" + url + "'>" + item.Title + "</a>");
                    sb.AppendLine("<hr />");
                }

                var htmlFormat = HtmlFormatHelper.CreateHtmlFormat(sb.ToString());
                request.Data.SetHtmlFormat(htmlFormat);
                return true;
            }
        }
    }
}